﻿using OperationPlugins;
using System;
using System.ComponentModel.Composition;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web.Security;
using TimeProject.Engine.DbContent;
using TimeProject.Engine.Security;
using WebMatrix.WebData;


namespace TimeProject.WebSite.Exports
{
    /// <summary>
    /// Initializes the database.
    /// </summary>
    [Export(typeof(IInitializable))]
    public class DbModelInitializer : IInitializable
    {
        void IInitializable.Initialize(InitializationContext context)
        {
            Database.SetInitializer<TimeProjectDbContext>(null);
                
            // Create the database if it does not exist on the server.
            using (var db =  RequestContext.CreateDbContext())
            {
                bool databaseExists = db.Database.Exists();

                if (databaseExists == false)
                {
                    ((IObjectContextAdapter) db).ObjectContext.CreateDatabase();
                }
            }

            // Initialize the membership system.
            WebSecurity.InitializeDatabaseConnection("TimeProjectConnection", "User", "Id", "Username", true);

            // Create missing user roles.
            string[] existingRoles = Roles.GetAllRoles();
            foreach (Tuple<UserRole, UserRoleMetadataAttribute> pair in UserRoles.GetAll())
            {
                string roleName = pair.Item2.Id;
                if (existingRoles.Contains(roleName) == false)
                {
                    Roles.CreateRole(roleName);
                }
            }


        }
    }
}
